import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

class CeshiDemo extends StatefulWidget {
  CeshiDemo({Key? key}) : super(key: key);

  @override
  _CeshiDemoState createState() => _CeshiDemoState();
}

class _CeshiDemoState extends State<CeshiDemo> with WidgetsBindingObserver {
  final titleController = TextEditingController();
  final FocusNode focusCode = FocusNode();
  double keyBordHeight = 0;

  @override
  void initState() {
    super.initState();
    // 初始化监听页面高度
    WidgetsBinding.instance?.addObserver(this);
    focusCode.addListener(() {
      if (focusCode.hasFocus) {
        hideKeyWord();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance?.removeObserver(this);
  }

  void hideKeyWord() {
    SystemChannels.textInput.invokeListMethod<void>('TextInput.hide');
    // SystemChannels.textInput.invokeListMethod<void>('TextInput.clearClient');
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance?.addPersistentFrameCallback(
      (_) {
        if (MediaQuery.of(Get.context!).viewInsets.bottom == 0) {
          setState(() {
            keyBordHeight = 0;
          });
        } else {
          if (MediaQuery.of(Get.context!).viewInsets.bottom == keyBordHeight) {
            return;
          }
          setState(() {
            keyBordHeight = MediaQuery.of(Get.context!).viewInsets.bottom;
          });
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        color: Colors.yellow,
        child: Column(
          children: [
            Expanded(
                child: Container(
                    width: double.infinity,
                    color: Colors.blue,
                    child: Column(
                      children: [
                        ElevatedButton(
                            onPressed: hideKeyWord, child: Text('隐藏键盘')),
                      ],
                    ))),
            Column(
              children: [
                TextField(
                  focusNode: focusCode,
                  controller: titleController,
                  keyboardType: TextInputType.emailAddress,
                  style: const TextStyle(color: Colors.blue, fontSize: 14),
                  cursorColor: Colors.red,
                  decoration:
                      InputDecoration(filled: true, fillColor: Colors.grey[50]),
                ),
                Container(
                  height: keyBordHeight,
                  child: Container(
                    color: Colors.yellow,
                    child: Text('24'),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
